package com.demo.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.demo.dto.Result;
import com.demo.entity.SeckillVoucher;
import com.demo.entity.VoucherOrder;
import com.demo.mapper.VoucherOrderMapper;
import com.demo.service.ISeckillVoucherService;
import com.demo.service.IVoucherOrderService;
import com.demo.utils.RedisIdWorker;
import com.demo.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Slf4j
@Service
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {

    @Resource
    private ISeckillVoucherService seckillVoucherService;

    @Resource
    private RedisIdWorker redisIdWorker;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private RedissonClient redissonClient;

    /**
     * 创建一个阻塞队列
     */
    private BlockingQueue<VoucherOrder> orderTasks = new ArrayBlockingQueue<>(1024 * 1024);

    /**
     * 开启一个线程池
     */
    private static final ExecutorService SECKILL_ORDER_EXECUTOR = Executors.newSingleThreadExecutor();

    /**
     * 初始化之后执行方法
     */
    @PostConstruct
    private void init(){
        SECKILL_ORDER_EXECUTOR.submit(new VoucherOrderHandler());
    }
    private class VoucherOrderHandler implements Runnable {

        @Override
        public void run() {
            while (true) {
                try {
                    //1，获取队列中的订单信息
                    VoucherOrder voucherOrder = orderTasks.take();
                    //2.创建订单
                    handlerVoucherOrder(voucherOrder);
                } catch (InterruptedException e) {
                    log.error("处理订单异常", e);
                }
            }
        }
    }

        private void handlerVoucherOrder(VoucherOrder voucherOrder) {
            //1.获取用户
            Long userId = voucherOrder.getUserId();
            //2.创建锁对象
            RLock lock = redissonClient.getLock("lock:order:" + userId);
            //3.获取锁
            boolean isLock = lock.tryLock();
            //4.判断获取锁是否成功
            if (!isLock) {
                //获取锁失败，返回错误或重试
                log.error("不允许重复下单");
                return;
            }
            try {
                proxy.createVoucherOrder(voucherOrder);
            }finally {
                lock.unlock();
            }
        }

    private static final DefaultRedisScript<Long> SECKILL_SCRIPT;
    static {
        //初始化
        SECKILL_SCRIPT = new DefaultRedisScript<>();
        SECKILL_SCRIPT.setLocation(new ClassPathResource("seckill.lua"));//执行脚本的位置
        SECKILL_SCRIPT.setResultType(Long.class);//返回Long类型
    }

    private IVoucherOrderService proxy;
    @Override
    public Result seckillVoucherLua(Long voucherId) {
        //获取用户
        Long userId = UserHolder.getUser().getId();
        //1.执行lua脚本
        Long result = stringRedisTemplate.execute(SECKILL_SCRIPT, Collections.emptyList(), voucherId.toString(), userId.toString());
        //2.判断结果是否为0
        int r = result.intValue();
        if (r != 0) {
            //2.1不为0 代表没有购买资格
            return Result.fail(r == 1 ? "库存不足" : "不能重复下单");
        }
        //2.2将下单信息保存到异阻塞队列
        VoucherOrder voucherOrder = new VoucherOrder();
        long orderId = redisIdWorker.nextId("order");
        //TODO 保存到阻塞队列
        voucherOrder.setId(orderId);
        //保存用户id
        voucherOrder.setUserId(userId);
        //保存代金券id
        voucherOrder.setVoucherId(voucherId);
        //2.3.放入阻塞队列
        orderTasks.add(voucherOrder);
        //3.获取代理对象
        proxy = (IVoucherOrderService) AopContext.currentProxy();
        //4.返回订单id
        return Result.ok(orderId);
    }


//    @Override
//    public Result seckillVoucher(Long voucherId) {
//        //1.查询优惠券
//        SeckillVoucher seckillVoucher = seckillVoucherService.getById(voucherId);
//        //2.判断秒杀是否开始
//        LocalDateTime beginTime = seckillVoucher.getBeginTime();
//        if (beginTime.isAfter(LocalDateTime.now())){
//            return Result.fail("秒杀尚未开始");
//        }
//        //3.判断秒杀是否结束
//        LocalDateTime endTime = seckillVoucher.getEndTime();
//        if (endTime.isBefore(LocalDateTime.now())){
//            return Result.fail("秒杀尚未开始");
//        }
//        //4.库存是否充足
//        Integer stock = seckillVoucher.getStock();
//        if (stock < 1){
//            return Result.fail("库存不足");
//        }
//        Long userId = UserHolder.getUser().getId();
//        //toString.intern()保证去常量池拿到同一个字符串userId
////        synchronized (userId.toString().intern()){
//            //锁住整个createVoucherOrder方法，事务完成提交订单之后，再去解锁 1.先获取锁 2，提交事务 3，释放锁
//            //此处的createVoucherOrder方法是this方法，不是被代理的对象
//
//        //创建锁对象
////        SimpleRedisLock lock = new SimpleRedisLock("Order" + userId, stringRedisTemplate);
//        RLock lock = redissonClient.getLock("lock:order" + userId);
//        //获取锁
//        boolean isLock = lock.tryLock();
//        //判断是否获取锁成功
//        if (!isLock){
//            //获取锁失败
//            return Result.fail("不允许重复下单");
//        }
//        try {
//            IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
//            //让代理对象去调用方法，才会被Spring管理
//            return proxy.createVoucherOrder(voucherId);
//        } finally {
//            //释放锁
//            lock.unlock();
//        }
////        }
//    }

//    @Transactional
//    //事务管理数据库的写操作
//    //封装下单的方法
//    public void createVoucherOrder(VoucherOrder voucherId){
//
//        //TODO 一人一单 查当前用户的id
//        Long userId = UserHolder.getUser().getId();
//        //TODO 查询订单
//        int count = query().eq("user_id", userId).eq("voucher_id", voucherId).count();
//        //TODO 判断是否存在
//        if (count > 0 ){
//            //记录已经存在了
//            return Result.fail("您已经购买过了");
//        }
//        //5.扣减库存的同时判断库存是否与查出的一致 CAS乐观锁解决超卖
//        boolean success = seckillVoucherService.update().setSql("stock = stock -1")
//                //where voucherId = #{voucherId}
//                .eq("voucher_id", voucherId)
//                //where stock = #{stock}
////                .eq("stock",seckillVoucher.getStock())
//                //where stock > 0
//                .gt("stock",0)
//                .update();
//        if (!success){
//            return Result.fail("库存不足");
//        }
//        //6。创建订单
//        VoucherOrder voucherOrder = new VoucherOrder();
//        //保存订单id
//        long orderId = redisIdWorker.nextId("order");
//        voucherOrder.setId(orderId);
//        //保存用户id
//        voucherOrder.setUserId(userId);
//        //保存代金券id
//        voucherOrder.setVoucherId(voucherId);
//        save(voucherOrder);
//        //7.返回订单id
//        return Result.ok(orderId);
//    }

    @Transactional
    //事务管理数据库的写操作
    //封装下单的方法
    public void createVoucherOrder(VoucherOrder voucherOrder){

        //TODO 一人一单 查当前用户的id
        Long userId = voucherOrder.getUserId();
        //TODO 查询订单
        int count = query().eq("user_id", userId).eq("voucher_id", voucherOrder.getVoucherId()).count();
        //TODO 判断是否存在
        if (count > 0 ){
            //记录已经存在了
            log.error("已经购买过了");
            return;
        }
        //5.扣减库存的同时判断库存是否与查出的一致 CAS乐观锁解决超卖
        boolean success = seckillVoucherService.update().setSql("stock = stock -1")
                //where voucherId = #{voucherId}
                .eq("voucher_id", voucherOrder.getVoucherId())
                //where stock = #{stock}
//                .eq("stock",seckillVoucher.getStock())
                //where stock > 0
                .gt("stock",0)
                .update();
        if (!success){
            log.error("库存不足");
            return;
        }
        save(voucherOrder);
    }
}
